package force;

import java.awt.event.KeyEvent;
import java.awt.geom.Point2D;
import java.util.Scanner;
import object.mass.Mass;
import sim.Simulation;

/**
 * A class that implements the Center of Mass global force.
 * @author Niel Lebeck and Wynne Lok
 *
 */
public class CenterMass extends GlobalForceSource {
    private static final double DEFAULT_CENTER_MASS_MAG = 10000;
    private static final double DEFAULT_CENTER_MASS_EXP = 2;
    
    private boolean myCenterMassOn;
    private double myCenterMassMag;
    private double myCenterMassExp;
    
    /**
     * 
     * @param line String
     */
    public CenterMass(String line) {
        Scanner s = new Scanner(line);
        String type = s.next();
        myCenterMassMag = s.nextDouble();
        myCenterMassExp = s.nextDouble();
        myCenterMassOn = true;
    }
    
    /**
     * 
     */
    public CenterMass() {
        myCenterMassMag = DEFAULT_CENTER_MASS_MAG;
        myCenterMassExp = DEFAULT_CENTER_MASS_EXP;
        myCenterMassOn = false;
    }
    
    /**
     * Calculate the center of mass force on the given Mass.
     * @param m Mass
     * @param sim Simulation
     * @return
     */
    @Override
    public Force getForce (Mass m, Simulation sim) {
        Point2D centerOfMass = sim.getCenterOfMass();
        Point2D massLocation = m.getCenter();
        double centerMassForceDir =
                Force.angleBetween(centerOfMass, massLocation);
        double centerMassForceMag = myCenterMassMag
                / Math.pow(Force.distanceBetween(massLocation, centerOfMass),
                        myCenterMassExp);
        Force result;
        if (myCenterMassOn) {
            result = new Force(centerMassForceDir, centerMassForceMag);
        }
        else {
            result = new Force(0, 0);
        }
        return result;
    }

    @Override
    public void toggle(int keycode) {
        if (keycode == KeyEvent.VK_M) {
            myCenterMassOn = !myCenterMassOn;
        }
    }

}
